import { Message } from 'element-ui';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
import { getUserToken, getLocalToken, getCookieTenant, setCookieTenant } from '@/lib/auth'; // get token from cookie
import { resetRouter } from './index';
// import i18n from '@/lib/lang/index';
import { loginOidc } from '@/lib/oidc_fun';
// import { encryptionJson } from '@/lib/cache';

NProgress.configure({ showSpinner: false }); // NProgress Configuration

// 页面标题
// const getPageTitle = (key, title) => {
//   const hasKey = i18n.te(`route.${key}`);
//   if (hasKey) {
//     const pageName = i18n.t(`route.${key}`);
//     return `${pageName} - ${title}`;
//   }
//   return `${title}`;
// };
export async function beforeRouter (to, from, next, store, router, extendRouterList, whiteList, initToDo) {
  NProgress.start();
  // set page title
  // document.title = getPageTitle(to.meta.title, store.getters.appTitle);
  // determine whether the user has logged in
  console.log('to------------from-------', to, from);
  const hasToken = getLocalToken() || await getUserToken();
  if (hasToken) {
    // 是否获取权限
    const hasRoles = store.getters.roles && store.getters.roles.length > 0;
    if (!hasRoles) {
      try {
        resetRouter();
        if (!store.state.app.isgetBadge) {
          // 获取用户信息
          await store.dispatch('user/getInfo');

          await store.dispatch('user/getFirstOrg');
          // 获取用户顶级机构列表
          await store.dispatch('user/getRootUnits');
          if (initToDo) {
            try {
              await store.dispatch('user/getCurrentUserType');
            } catch (error) {
              console.error(error);
            }
            await initToDo(to, next, from);
          }
          store.dispatch('app/setIsGetBadge', true);
          console.log('next-------', to, from);
          next({ ...to, replace: true });
          NProgress.done();
        }
      } catch (error) {
        // remove token and go to login page to re-login
        // await store.dispatch('user/resetToken');
        Message.error(error || 'Has Error');
        NProgress.done();
      }
    }
  } else if (!testWhiteList(whiteList, to.path)) {
    let href = window.location.href;
    href = href.indexOf('#') > -1 ? (href.indexOf('?') > -1 ? (href + '&') : (href + '?')) : (href + '#/?');
    href = href.replace(/loginRandom=[0-9]+|loginRandom=/g, '').replace(/&&+/g, '&').replace('?&', '?');
    href = href + 'loginRandom=' + new Date().getTime();
    let tenantId = getUrlTenantId(to) || getCookieTenant() || '';
    if (tenantId) {
      setCookieTenant(tenantId);
    }
    tenantId = tenantId + '___' + ENVIR;
    loginOidc({
      state: window.btoa(href),
      acr_values: tenantId ? window.btoa(tenantId) : ''
    }); // 跳转登录
    NProgress.done();
  } else {
    next();
    NProgress.done();
  }
  NProgress.done();
  return true;
}

// 获取url中的tenantid
function getUrlTenantId (to) {
  let _returnTenantId = '';
  if (to.query.tenantid) {
    _returnTenantId = to.query.tenantid;
  } else if (to.params.tenantId) {
    _returnTenantId = to.params.tenantId.replace('t__', '');
  } else if (to.path.indexOf('t__') > -1) {
    const _pathList = to.path.split('/');
    _pathList.map(item => {
      if (item.indexOf('t__') > -1) {
        const _t = item.replace('t__', '');
        if (_t.indexOf('_') > -1) {
          _returnTenantId = _t.split('_')[0];
        } else {
          _returnTenantId = _t;
        }
      }
    });
  }
  console.log(window.location.search)
  // if(window.location.href.indexOf('game')===-1) {
  //   return _returnTenantId;
  // } else {
  //   return process.env.VUE_APP_Get_TenantId;
  // }
  return _returnTenantId;
}

export function testWhiteList (whiteList, path) {
  if (!whiteList) {
    return false;
  }
  if (whiteList.includes(path)) {
    return true;
  }
  for (const i in whiteList) {
    if (typeof whiteList[i] !== 'string') {
      if (whiteList[i].test(path)) {
        return true;
      }
    }
  }
  // if(window.location.href.indexOf('game')===-1) {
  //   return false;
  // } else {
  //   return true;
  // }
  return false;

}

export function afterRouter () {
  NProgress.done();
}
